#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>

enum my_command
{
	CMD_NONE,
	CMD_READ,
	CMD_WRITE,
	CMD_ERASE,
	CMD_BUTT
};
static int input_file_set =0;
static int output_file_set =0;
static char *file;

static enum my_command cmd;

static void usage(char *base)
{
	printf("%s: sample for getopt test operation.\n"
			,base);
	exit(-1);
}
static void process_option(int argc,char *argv[])
{
	int op;

	while((op = getopt(argc,argv,"RWE:i:o:")) != -1){
		switch(op){
			case 'R':
				cmd = CMD_READ;
				printf("command read\n");
				break;
			case 'W':
				cmd = CMD_WRITE;
				printf("cmmand write\n");
				break;
			case 'E':
				cmd = CMD_ERASE;
				printf("command erase\n");
				break;
			case 'i':
				input_file_set =1;
				file = optarg;
				printf("input file: %s\n",file);
				break;
			case 'o':
				output_file_set = 1;
				file = optarg;
				printf("output file: %s\n",file);
				break;
			case 'h':
			case 'H':
			default:
				usage(argv[0]);
				exit(0);

		}
	}
}
static int check_param(void)
{
	if(cmd != CMD_ERASE && cmd != CMD_WRITE && cmd != CMD_READ){
		printf("command %d not right!\n",cmd);
		return -1;
	}
	if(cmd == CMD_ERASE && (output_file_set || input_file_set)){
		printf("cmd is erase, but file set!\n");
		return -1;
	}
	if(cmd == CMD_WRITE && output_file_set){
		printf("cmd is write but output file set!\n");
		return -1;
	}
	if(cmd == CMD_READ && input_file_set){
		printf("cmd is read but input file set\n");
		return -1;
	}
	if(cmd == CMD_READ && input_file_set){
		printf("cmd is read but input file set\n");
		return -1;
	}
	if(input_file_set && output_file_set){
		printf("input file and output file set both!");
		return -1;
	}
	return 0;
}
int main(int argc,char *argv[])
{
	process_option(argc,argv);

	if(check_param())
		usage(argv[0]);
	
	if(cmd == CMD_READ)
		printf("hi read\n");
	else if(cmd == CMD_WRITE)
		printf("hi write\n");
	else if(cmd == CMD_ERASE)
		printf("hi rease");
	else
		usage(argv[0]);
	exit(0);
}
